import matplotlib
import numpy as np
import matplotlib.pyplot as plt
from skimage.filters.lpi_filter import forward
from mpl_toolkits.mplot3d import Axes3D


matplotlib.rcParams['axes.unicode_minus'] = False  # 解决负号问题
plt.rcParams['font.sans-serif'] = ['SimHei']
x_data = [1.0, 2.0, 3.0, 4.0]
y_data = [2.0, 4.0 ,6.0, 8.0]

def forward(x):
    return x * w + b

def loss(x, y):
    y_pred = forward(x)
    return (y_pred - y) * (y_pred - y)

w_list = []
b_list = []
mse_list = []
for w in np.arange(0.0, 4.1, 0.1):
    for b in np.arange(0.0, 4.1, 0.1):
        print('w = ',w,'b = ', b)
        l_sum = 0
        for x_val, y_val in zip(x_data, y_data):
            y_pred_val = forward(x_val)
            loss_val = loss(x_val, y_val)
            l_sum += loss_val
            print('\t', x_val, y_val, y_pred_val, loss_val)
        print('MSE = ',l_sum / 3)
        b_list.append(b)
        mse_list.append(l_sum / 3)
        w_list.append(w)

# 绘制图像
plt.plot(w_list, mse_list)
plt.ylabel('Loss')
plt.xlabel('w')
plt.show()

# 绘制三维
fig = plt.figure(figsize=(20,20), dpi = 100)
ax = fig.add_subplot(projection='3d')
# 使用plot_trisurf函数在三维坐标系中绘制一个三角曲面图。
# 设置曲面的颜色映射为'viridis'，这是一个从紫色到黄色的颜色渐变。设置曲面的边缘颜色为透明，这样就不会看到网格线。
ax.plot_trisurf(w_list, b_list, mse_list, cmap='viridis', edgecolor='none')
ax.set_xlabel("w", size = 15)
ax.set_ylabel("b", size = 15)
ax.set_zlabel("loss", size = 15)

plt.show()
